package com.apes.scm.masterdata.party.model;

import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = SupplierLogistic.CONST_TABLE_NAME)
public class SupplierLogistic extends Model {

    public static final String CONST_TABLE_NAME = "mas_supplier_logistic";

    @Id
    @Column(name = "id")
    @ApesGenerator(code = CONST_TABLE_NAME, name = "供应商物流扩展表")
    @Comment("单号")
    private String id;


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "supplier_id", referencedColumnName = "id")
    @Comment("供应商编码")
    private PartyRole supplier;

    @Comment("公司")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id", nullable = false)
    private PartyRole company;

    /***
     * 供应商送达仓
     */
    @OneToMany(mappedBy = "supplierLogistic", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<SupplierReachItem> supplierReachItems = new ArrayList<>();

    public List<SupplierReachItem> getSupplierReachItems() {
        for (SupplierReachItem item : supplierReachItems) {
            item.setSupplierLogistic(this);
        }
        return supplierReachItems;
    }


    /***
     * 供应商发货仓
     */
    @OneToMany(mappedBy = "supplierLogistic", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<SupplierShipItem> supplierShipItems = new ArrayList<>();

    public List<SupplierShipItem> getSupplierShipItems() {
        for (SupplierShipItem item : supplierShipItems) {
            item.setSupplierLogistic(this);
        }
        return supplierShipItems;
    }


    @Transient
    private PartyRole _creator;

    @Transient
    public PartyRole get_creator() {
        if(this.getCreator() == null) return null;
        return SpringManager.getBean(PartyRoleRepository.class).findOne(this.getCreator());
    }
}
